package cn.fx.controller;

import cn.fx.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@RestController
@RequestMapping("/order")
@DefaultProperties(defaultFallback = "getFallbackMethod")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getById/{id}")
    //标记熔断
    @HystrixCommand
    //@HystrixCommand(fallbackMethod = "getByIdFallback") //开启熔断
    public User getById(@PathVariable("id") Long id){

        //记录时间
        System.out.println(new Date().toLocaleString());
        System.out.println(1);

        //使用restTemplate发送请求,必须加上http
        //String url = "http://localhost:10020/user/getById/" + id;
        //拿到要调用服务的应用名称后，相当于拿到了该服务集群
        String url = "http://user-server/user/getById/" + id;

        User forObject = restTemplate.getForObject(url, User.class);
        //执行后的时间
        System.out.println(new Date().toLocaleString());

        return forObject;
    }

    //该方法就是降级方法，参数和返回值必须一致，方法名称就是fallbackMethod名称
    public Object getByIdFallback(@PathVariable("id") Long id){
        //降级方法，返回得数据就是兜底数据
        return new User(-1L,"熔断触发","网路异常，稍后重试");
    }

    //统一托底方法
    public User getFallbackMethod(){
        //降级方法，返回得数据就是兜底数据
        return new User(-1L,"熔断触发","网路异常，稍后重试");
    }
}
